package com.useeinfo.oa.modules.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.base.entity.Message;
import com.useeinfo.oa.modules.base.enums.MessageTypeEnum;
import com.useeinfo.oa.modules.repair.enums.RepairOrderStatusEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.*;

/**
 * @Auther: xudong.sun
 * @Date: 2019/1/15 16:00
 * @Description:
 */
@Repository("messageDao")
public class MessageDao implements CrudDao<Message> {


    private final static Logger logger = LoggerFactory.getLogger(MessageDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new LinkedHashMap<>();

        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }

        String enterpriseId = queryHash.get("enterpriseId");
        if (StringUtils.isNotBlank(enterpriseId)) {
            conditionHash.put("s.enterprise.id = ?{paramIndex}", StringConverters.null2Long(enterpriseId));
        }
        String sendToUserId = queryHash.get("sendToUserId");
        if(StringUtils.isNotBlank(sendToUserId)){
            conditionHash.put("s.sendToUser.id = ?{paramIndex}",StringConverters.null2Long(sendToUserId));
        }

        String searchParam = queryHash.get("searchParam");
        if(StringUtils.isNotBlank(searchParam)){
            conditionHash.put("(s.title like ?{paramIndex} or s.content like ?{paramIndex})",'%' + searchParam + '%');
        }
        String deviceType = queryHash.get("deviceType");
        if(StringUtils.isNotBlank(deviceType)){
            conditionHash.put("s.deviceType = ?{paramIndex}",deviceType);
        }

        String deviceToken = queryHash.get("deviceToken");
        if(StringUtils.isNotBlank(deviceToken)){
            conditionHash.put("(s.deviceToken = ?{paramIndex})",deviceToken);
        }

        String readStatus = queryHash.get("readStatus");
        if(StringUtils.isNotBlank(readStatus)){
            conditionHash.put("s.readStatus = ?{paramIndex}",StringConverters.null2Boolean(readStatus));
        }

        String messageType = queryHash.get("messageType");
        if (StringUtils.isNotBlank(messageType)) {
            String[] statusArray = messageType.split(",");
            for (int i = 0; i < statusArray.length; i++) {
                if (i == 0) {
                    String k = statusArray.length == 1 ? "messageTypeEnum = ?{paramIndex} " : "(messageTypeEnum = ?{paramIndex} ";
                    conditionHash.put(k, MessageTypeEnum.valueOf(statusArray[i].trim()));
                } else if (i == statusArray.length - 1) {
                    conditionHash.put("or messageTypeEnum = ?{paramIndex}) ", MessageTypeEnum.valueOf(statusArray[i].trim()));
                } else {
                    String k = String.format("or messageTypeEnum = ?{paramIndex} %" + i + "s", "");
                    conditionHash.put(k, MessageTypeEnum.valueOf(statusArray[i].trim()));
                }
            }
        }

        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from Message s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<Message> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from Message s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<Message> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, Message.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public Message findModel(Long id) {
        return entityManager.find(Message.class, id);
    }

    @Override
    public Integer add(Message model) {
        model.setCreateDate(new Date());
        entityManager.persist(model);
        logger.info("MessageDaoImpl添加message成功！");
        return 1;
    }

    @Override
    public Integer update(Message model) {
        model.setUpdateDate(new Date());
        entityManager.merge(model);
        return 1;
    }

    @Override
    public Integer delete(Long id) {
        Message message = entityManager.find(Message.class, id);
        entityManager.remove(message);
        return 1;
    }

    @Override
    public Integer deleteLogic(Message model) {
        model.setDeleteStatus(true);
        return 1;
    }
}
